<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="信息配置">
        <el-form
          ref="dataForm"
          :model="configurationMap"
          :rules="rules"
          label-width="300px"
          class="demo-ruleForm"
        >
          <el-form-item label="在线咨询按钮背景" prop="vip_rights">
            <el-upload
              :action="uploadUrl"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemoveButton_backg"
              ref="upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :headers="headers"
              v-model:file-list="online_consultation_button_backg"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <div class="tip">请上传306*75像素的图片</div>

          <el-form-item label="在线咨询背景" prop="privacy_statement">
            <el-upload
              :action="uploadUrl"
              :on-success="online_consulting_backSuccess"
              :on-remove="handleRemoveConsulting_back"
              :on-preview="handlePictureCardPreview"
              ref="upload"
              list-type="picture-card"
              :headers="headers"
              v-model:file-list="online_consulting_back"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>

          <div class="tip">请上传343*436像素的图片</div>

          <el-form-item label="上传落地页图片" prop="privacy_statement">
            <div style="display: flex; flex-direction: column">
              <el-input
                class="e-input"
                v-model="configurationMap.landing_page_name"
                placeholder="请输入落地页标题"
                clearable
                @keyup.enter="handleQuery"
              />

              <image-uploads
                v-model="configurationMap.landing_page_img"
                limit="100"
              ></image-uploads>
            </div>
          </el-form-item>

          <!-- <el-form-item label="预约码背景" prop="privacy_statement">
            <el-upload
              :action="uploadUrl"
              :on-success="reservationBackg_Success"
              ref="upload"
              :on-preview="handlePictureCardPreview"
              list-type="picture-card"
              :on-remove="handleRemoveCode_backg"
              :headers="headers"
              v-model:file-list="reservation_code_backg"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item> -->
          <div class="dialog-footer">
            <el-button type="primary" @click="updateMap">确定 </el-button>
            <el-button @click="getList()">取消</el-button>
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系统配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="configurationRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="key名字" prop="keyName">
          <el-input v-model="form.keyName" placeholder="请输入key名字" />
        </el-form-item>
        <el-form-item label="内容" prop="keyValue">
          <image-uploads v-model="form.keyValue"></image-uploads>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Configuration">
import {
  listConfiguration,
  listConfigurationMap,
  updateConfigurationMap,
  getConfiguration,
  delConfiguration,
  addConfiguration,
  updateConfiguration,
} from "@/api/business/configuration";
import ImageUpload from "@/components/ImageUpload/index.vue";
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();

const configurationList = ref([]);
const configurationMap = ref({});
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeName = ref("0");
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/system/oss/upload");
console.log(uploadUrl, 99999999);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    keyName: undefined,
    keyValue: undefined,
  },
  rules: {
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    keyName: [{ required: true, message: "key名字不能为空", trigger: "blur" }],
    keyValue: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询系统配置列表 */
function getList() {
  loading.value = true;
  listConfiguration(queryParams.value).then((response) => {
    configurationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 图片失败拦截
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}
// 图片上传成功返回图片地址
function handleUploadSuccess(res, file) {
  if (online_consultation_button_backg.value.length === 2) {
    online_consultation_button_backg.value.shift();
  }
  configurationMap.value.online_consultation_button_backg = res.data.url;
}

function online_consulting_backSuccess(res) {
  if (online_consulting_back.value.length === 2) {
    online_consulting_back.value.shift();
  }

  configurationMap.value.online_consulting_back = res.data.url;
}
function reservationBackg_Success(res) {
  if (reservation_code_backg.value === 2) {
    reservation_code_backg.value.shift();
  }

  configurationMap.value.reservation_code_backg = res.data.url;
}
function handleRemoveButton_backg(res) {
  configurationMap.value.online_consultation_button_backg = "";
}
function handleRemoveConsulting_back() {
  configurationMap.value.online_consulting_back = "";
}
function handleRemoveCode_backg() {
  configurationMap.value.reservation_code_backg = "";
}
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
function handlePictureCardPreview(uploadFile) {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
}
// const online_consultation_button_backg   online_consulting_back    reservation_code_backg
const online_consultation_button_backg = ref([]);
const online_consulting_back = ref([]);
const reservation_code_backg = ref([]);
getListMap();

function getListMap() {
  listConfigurationMap().then((response) => {
    configurationMap.value = response.data;
    if (response.data.online_consultation_button_backg) {
      online_consultation_button_backg.value = [
        { url: response.data.online_consultation_button_backg },
      ];
    }
    if (response.data.online_consulting_back) {
      online_consulting_back.value = [
        { url: response.data.online_consulting_back },
      ];
    }
    if (response.data.reservation_code_backg) {
      reservation_code_backg.value = [
        { url: response.data.reservation_code_backg },
      ];
    }

    console.log(configurationMap.value);
  });
}

function updateMap() {
  updateConfigurationMap(configurationMap.value).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
    getListMap();
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    keyName: null,
    keyValue: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
  };
  proxy.resetForm("configurationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加系统配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getConfiguration(_id).then((response) => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改系统配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["configurationRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateConfiguration(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addConfiguration(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除系统配置编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delConfiguration(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/configuration/export",
    {
      ...queryParams.value,
    },
    `configuration_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style lang="scss" scoped>
.tip {
  transform: translateY(-20px);
  margin-left: 300px;
  color: #409eff;
}
.e-input {
  width: 300px;
  margin-bottom: 20px;
}
</style>
